package pub.elephants.socket.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import pub.elephants.net.body.ElephantsRequest;
import pub.elephants.net.body.ElephantsResponse;
import pub.elephants.serializable.ElephantsSerializable;
import pub.elephants.socket.netty.core.NettyDecoder;
import pub.elephants.socket.netty.core.NettyEncoder;

public class NettyClientPoolProxy {
    private Channel channel;

    public void createProxy(String host, int port, final ElephantsSerializable serializer) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new NettyEncoder(serializer, ElephantsRequest.class))
                                .addLast(new NettyDecoder(serializer, ElephantsResponse.class))
                                .addLast(new NettyClientHandler());
                    }
                })
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, true);
        this.channel = bootstrap.connect(host, port).sync().channel();
    }

    public Channel getChannel() {
        return this.channel;
    }

    public boolean isValidate() {
        if (this.channel != null) {
            return this.channel.isActive();
        }
        return false;
    }

    public void close() {
        if (this.channel != null) {
            if (this.channel.isOpen()) {
                this.channel.close();
            }
        }
    }

    public void send(ElephantsRequest request) throws Exception {
        this.channel.writeAndFlush(request).sync();
    }

}
